<template>
    <Card class="config" dis-hover :padding='0'>
        <p slot='title'>
            房间基础用电配置
            <Button type="ghost" size="small" class="btn-left" :disabled="isMogoroomAuth" @click="saveRoomEleConfig">保存修改</Button>
        </p>
        <div style="padding: 0 20px">
            <Alert type="error" show-icon v-if="isMogoroomAuth">当前商户已对接第三方平台，如需修改，请解除授权</Alert>
        </div>
        <div class="ele-common-cfg-wrap">
            <Row type="flex" :gutter="16" align="middle" class="ele-common-cfg-item">
                <Col span="2.5">
                    房间电价：
                </Col>
                <Col span="5">
                    <Select v-model="elePriceType" :disabled="isMogoroomAuth">
                        <Option v-for="item in elePrice" :value="item.value" :key="item.value">{{ item.label }}</Option>
                    </Select>
                </Col>
                <Col span="8" v-if="elePriceType == 2">
                    <InputNumber :disabled="isMogoroomAuth" style="width:180px" v-model="elePriceValue" :min="0" :max="100" :formatter="formatInput"/>
                        元/度
                    </InputNumber>
                </Col>
            </Row>

            <Row type="flex" :gutter="16" align="middle" class="ele-common-cfg-item">
                <Col span="2.5">
                    付费模式：
                </Col>
                <Col span="5" v-if="(!isEdit) || (!ifHasElemeter)">
                    <Select v-model="payModesType" :disabled="isMogoroomAuth">
                        <Option v-for="item in payModes" :value="item.value" :key="item.value">{{ item.label }}</Option>
                    </Select>
                </Col>
                <Col span="5" v-if="payModesType == 2">
                    <Select v-model="homePayModeType" style="width:180px" :disabled="isMogoroomAuth">
                        <Option v-for="item in homePayModes" :value="item.type" :key="item.type">{{ item.text }}</Option>
                    </Select>
                </Col>
            </Row>

            <Row type="flex" :gutter="16" align="middle" class="ele-common-cfg-item" v-show="isPostPaid">
                <Col span="2.5">
                    透支额度：
                </Col>
                <Col span="5">
                    <InputNumber
                        v-model="overdraftAmountValue"
                        :formatter="formatInput"
                        :min="0" :max="999"
                        style="width:100%"
                        :disabled="(payModesType == 1 && !parentIsPostPaid) || isMogoroomAuth">
                    </InputNumber>
                </Col>
                <Col span="4">
                    度
                </Col>
            </Row>

            <Row type="flex" :gutter="16" align="middle" class="ele-common-cfg-item" v-show="isPostPaid">
                <Col span="2.5">
                    断电提醒：
                </Col>

                <Col span="5">
                    <Select
                        style="width: 100%;"
                        v-model="lowWarnValue"
                        :disabled="(payModesType == 1 && !parentIsPostPaid) || isMogoroomAuth">
                        <Option v-for="item in LowWarnValues" :value="item" :key="item">{{ item }}</Option>
                    </Select>
                </Col>

                <Col span="4">
                    度
                </Col>
            </Row>
        </div>

    </Card>
</template>
<script>
import { mapGetters } from 'vuex'
import util from '@/libs/util'
import { http, api } from '@/libs/http'
import { ElemeterPayMode, LowWarnValues } from '@/libs/const'
export default {
  name: 'config_index',
  props: {
    room: Object
  },
  created () {
    // console.log('room', this.room);
    this.getDetail()
    this.getIfHasElemeter()
  },
  computed: {
    isPostPaid () {
      return (this.payModesType === 1 && !this.parentIsPostPaid) || (this.payModesType === 2 && this.homePayModeType === 1)
    },
    ...mapGetters([ 'isMogoroomAuth' ])
  },
  data () {
    return {
      LowWarnValues,
      currentPayType: null, // 记录现在的支付方式
      parentIsPostPaid: false, // 房源默认为后付费
      // 电价
      elePriceType: null,
      elePriceValue: 0,
      elePrice: [],

      // 付费模式
      payModes: [],
      payModesType: null,

      homePayModes: [
        // 房源付费模式
        ElemeterPayMode.properties[ElemeterPayMode.PREPAID], // 预付费
        ElemeterPayMode.properties[ElemeterPayMode.POSTPAID] // 后付费
      ],
      homePayModeType: null,

      // 透支额度
      overdraftAmountValue: 10,
      parentOverdraftAmountValue: null,

      // 断点提醒
      lowWarnValue: 10,
      parentLowWarnValue: null,

      initData: null,

      isEdit: false,
      ifHasElemeter: false
    }
  },
  watch: {
    homePayModeType (newVal, oldVal) {
      if (oldVal !== null) this.currentPayType = newVal
    },
    payModesType (newVal, oldVal) {
      if (oldVal !== null) {
        if (newVal === 1) {
          this.parentIsPostPaid ? (this.currentPayType = 2) : (this.currentPayType = 1)
          this.overdraftAmountValue = this.parentOverdraftAmountValue
          this.lowWarnValue = this.parentLowWarnValue
        } else this.currentPayType = this.homePayModeType
      }
    },
    currentPayType (newVal, oldVal) {
      if (oldVal !== null) {
        this.$Modal.warning({
          title: newVal === 2 ? '预付费切换后付费' : '后付费切换预付费',
          content:
                        newVal === 2
                          ? '<p>切换后，剩余电量及充值电量将清 零。为避免影响使用，建议记录相关数据后切换</p>'
                          : '<p>切换后，如电表剩余电量不足时将 自动断电。为避免影响使用，建议切换后，及时充值<p>',
          okText: '我已知悉'
        })
      }
    }
  },
  methods: {
    async getIfHasElemeter () {
      const roomInfo = await http.req(api.room_info, [this.room.roomId], null)
      this.ifHasElemeter =
                roomInfo &&
                roomInfo.devices &&
                roomInfo.devices.some(item => {
                  return item.device_type === 3
                })
      util.log('房间是否有电表', this.ifHasElemeter)
    },

    formatInput (newVal) {
      if (newVal < 0) {
        return 1
      } else {
        return newVal
      }
    },

    async getDetail () {
      let res = await http.req(api.room_elemeter_setting, [this.room.roomId], null)

      if (!res) return

      this.initData = res // 保存初始数据

      let { ele_price, low_warn, overdraft_amount, pay_type } = res // 获取电价，付费模式，透支额度，断点提醒

      // 电价
      this.elePrice = []
      this.elePrice.push(
        {
          value: 1,
          label: `房源指导: ${ele_price.parent_value ? `${ele_price.parent_value}元/度` : '未知'}`
        },
        {
          value: 2,
          label: '房间自定义'
        }
      )

      if (ele_price.value) {
        // 如果存在自定义电价
        this.elePriceType = 2
        this.elePriceValue = Number(ele_price.value)
      } else {
        this.elePriceType = 1
      }

      // 透支额度
      this.parentOverdraftAmountValue = +overdraft_amount.parent_value
      this.overdraftAmountValue = Number(overdraft_amount.value || overdraft_amount.parent_value || 1)

      // 低电提醒

      this.lowWarnValue = Number(low_warn.value || low_warn.parent_value || 1)
      this.parentLowWarnValue = +low_warn.parent_value

      // 付费模式
      this.payModes = []
      this.payModes.push(
        {
          value: 1,
          label: `房源指导: ${pay_type.parent_value ? `${pay_type.parent_value === 1 ? '预付费' : '后付费'}` : '未知'}`
        },
        {
          value: 2,
          label: '房间自定义'
        }
      )

      if (pay_type.parent_value === 2) this.parentIsPostPaid = true

      if (pay_type.value) {
        // 如果存在自定义付费模式
        this.isEdit = true
        this.payModesType = 2
        pay_type.value === 1 ? (this.homePayModeType = 1) : (this.homePayModeType = 2)
        this.currentPayType = pay_type.value
      } else {
        this.payModesType = 1
        this.homePayModeType = 1
        this.parentIsPostPaid ? (this.currentPayType = 2) : (this.currentPayType = 1)
      }
    },
    async saveRoomEleConfig () {
      // 保存用电配置
      if (this.isMogoroomAuth) {
        this.$Message.error('蘑菇授权商户无法修改')
        return
      }
      let params = {}

      if (this.elePriceType === 2) {
        if (!this.elePriceValue) {
          this.$Message.info('房间电价设置错误')
          return
        }
        params.ele_price = this.elePriceValue
      }

      if (this.payModesType === 2 && this.homePayModeType) {
        params.pay_type = this.homePayModeType
      }

      if (this.payModesType === 2 && this.homePayModeType === 1) {
        if (!this.overdraftAmountValue || this.overdraftAmountValue < 0.01) {
          this.$Message.info('透支额度最少为0.01')
          return
        }
        params.overdraft_amount = +this.overdraftAmountValue.toFixed(2)
        params.low_warn = this.lowWarnValue
      }

      if (params.ele_price > 5) {
        this.$Message.info('电价设置最大不能超过5元')
        return
      }

      let res = await http.req(api.room_elemeter_setting_update, [this.room.roomId], params)

      if (res) {
        this.$Message.success('用电设置保存成功!')
        this.getDetail()

        // 刷新房源房间列表
        // refreshRoom(this.room.homeId, this.room.roomId)
      }
    }
  }
}
</script>
<style lang="less">
@import '../../styles/common.less';
.config {
    background-color: #fff !important;
    font-size: 14px;
    &-room {
        padding: 20px 25px;
        &-title {
            color: #5b5b5b;
        }
    }
}
.ele-common-cfg {
    &-item {
        padding: 6px 20px;
    }
    &-wrap {
        padding-top: 10px;
        padding-bottom: 20px;
    }
}
.btn-left {
    margin-left: 15px;
}
.ivu-card-head p {
    border-radius: 0;
}
</style>
